<template>
  <div>
    <!-- 返利池查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>
    <FilterTables
      ref="table"
      columnsRef="wkcRebatePoolQuery"
      :columns="columns"
      :isSelectColumn="false"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="(columns) => (this.columns = columns)"
    >
      <template slot="controls">
        <multiuse-button size="small" type="primary" @click="addHandle()">导 出</multiuse-button>
      </template>
    </FilterTables>
    <BaseDialog :visible.sync="isClick" :title="'余额锁定明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <FrostAmountDetail :rowData="detailData" @close="detailclose" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList, exportList } from '@/api/omFinanceP/RebateManage/RebatePoolQuery';
import { exportExcelFile } from '@/utils';
import { region } from '@/api/cms-common/region'; //行政区域
import FrostAmountDetail from './FrostAmountDetail';
import { getRegion, getCommunity, getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index'; //事业部，办事处
import { dealerCommon, DICT_CODE } from '@/api/cms-api/origin/commonDealerType'; //经销商类型工具类
export default {
  name: 'RebatePoolQuery',
  mixins: [dictionary, region, dealerCommon],
  data() {
    this.BaseTable = null;
    return {
      ORG_TYPE_MARKETING_WAR_AREA: 15061015, // 营销战区
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      detailData: {},
      visible: false,
      isClick: false,
      handleType: '',
    };
  },
  components: { FrostAmountDetail },
  mounted() {
    this.initProvince();
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA, 'areaId');
  },
  methods: {
    detailclose(val) {
      this.isClick = false;
    },
    //获取顶层组织数据
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async addHandle() {
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let json = this.fetchParams;
          this.exportLoading = true;
          exportList(json)
            .then((response) => {
              exportExcelFile(response.data, '返利池查询');
            })
            .catch((err) => {});
          this.exportLoading = false;
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
    async editHandle(data, type) {
      this.detailData = data;
      this.isClick = true;
    },
    formatNumber(value) {
      value += '';
      if (value.slice(-1) === '.') return value;
      value = value.replace(/,\s+/g, '');
      const list = value.split('.');
      const prefix = list[0].charAt(0) === '-' ? '-' : '';
      let num = prefix ? list[0].slice(1) : list[0];
      let result = '';
      while (num.length > 3) {
        result = `, ${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
      }
      if (num) {
        result = num + result;
      }
      return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: (props) => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'SELECT',
          label: '是否有可用余额',
          fieldName: 'isAvailAmount',
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'RANGE_DATE',
          label: '统计日期',
          fieldName: 'accountDateStart|accountDateEnd',
          dateType: 'exactdaterange',
          placeholder: '请选择',
        },
        {
          type: 'RENDER_FORM_ITEM',
          labelWidth: '0',
          render: () => {
            return (
              <el-tooltip class="item" effect="dark" content="统计日期查询仅支持按时间段查询累计入账和累计出账，其他金额一直显示当前统计值；" placement="right">
                <i class="desc-icon el-icon-info"></i>
              </el-tooltip>
            );
          },
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '累计入账',
          dataIndex: 'totalInAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '累计出账',
          dataIndex: 'totalOutAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '返利余额',
          dataIndex: 'balanceAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '预扣金额',
          dataIndex: 'frostAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
          render: (props) => {
            // if (props.row.frostAmount != 0) {
            return (
              <el-link type="warning" underline={true} onClick={() => this.editHandle(props.row)}>
                {this.formatNumber(Number(props.row.frostAmount).toFixed(2))}
              </el-link>
            );
            // } else {
            //   return <span>{this.formatNumber(Number(props.row.frostAmount).toFixed(2))}</span>;
            // }
          },
          // render: (p) => {
          //   return (
          //     <span class="discount" onClick={() => this.editHandle(p.row, 2)}>
          //       {this.formatNumber(Number(p.row.frostAmount).toFixed(2))}
          //     </span>
          //   );
          // },
        },
        {
          title: '冻结金额',
          dataIndex: 'frozenAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '可用余额',
          dataIndex: 'availableAmount',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '账户状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2111'),
          render: (props) => {
            return <span>{this.createDictText(props.row.status, '2111')}</span>;
          },
        },
        {
          title: '最后更新日期',
          dataIndex: 'updatedAt',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
